package com.sntk.organauthomanager.domain.model;

import com.sntk.organauthomanager.infrastructure.exception.DataNoLegalException;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName: AssignResourcesToUserService
 * @author: wgchao
 * @createTime: 2020/9/13 3:21 PM
 * @Description: 为账户赋权
 */
public class AssignResourcesToUserService {

    public UserResource assign(User user, UserAffiliate userAffiliate, Organization organization, List<Resource> resources){
        user.normalException();
        organization.normalException();
        if(!user.getInstitutionNumber().equals(organization.getInstitutionNumber())){
            if(userAffiliate == null){
                throw new DataNoLegalException("账户与该机构无关联");
            }else if(!userAffiliate.isAffiliates(organization.getInstitutionNumber())){
                throw new DataNoLegalException("账户与该机构无关联");
            }
        }
        if(resources == null || resources.isEmpty()){
            //账户空权限
            return new UserResource(new UserResourceIdentify(user.getUname(), organization.getInstitutionNumber()), null);
        }
        Set<String> aresources = new HashSet<>();
        for(Resource resource : resources){
            resource.normalException();
            aresources.add(resource.getMark());
        }
        return new UserResource(new UserResourceIdentify(user.getUname(), organization.getInstitutionNumber()), aresources);
    }
}
